import { SignJWT } from "jose";
import type { NextApiRequest, NextApiResponse } from "next";
import CryptoJS from "crypto-js";
import { PrismaClient } from "@prisma/client";
import { get } from "@/utils/_";

export default async function handler(
  request: NextApiRequest,
  response: NextApiResponse
) {
  const prisma = new PrismaClient();
  const body = JSON.parse(request.body);
  const user = await prisma.user.findFirst({
    where: {
      account: body.account,
    },
    select: {
      id: true,
      name: true,
      account: true,
      password: true,
      salt: true,
    },
  });

  if (!user) return response.json({ code: 400, message: "用户不存在" });

  const encodedPassword = CryptoJS.MD5(
    `${get(body, "password")}${user.salt}`
  ).toString();

  if (user.password !== encodedPassword) {
    return response.json({ code: 400, message: "密码错误" });
  }

  const token = await new SignJWT(user)
    .setProtectedHeader({ alg: "HS256" })
    .setIssuedAt()
    .setExpirationTime("7d")
    .sign(Buffer.from(process.env.JWT_SECRET as string));
  response.status(200).json({ code: 200, message: "登录成功", token });
}
